<?php


namespace App\Repositories\Lottery;

use App\Traits\Singleton;
use App\Models\MainDB\Lottery\UserStatDate as Model;
use Carbon\Carbon;

class UserStatDateRepository
{
    use Singleton;

    public function inc(int $userId, array $data)
    {
        $date  = Carbon::now()->toDateString();
        $model = $this->one(['date' => $date, 'user_id' => $userId], false, true);
        if (!$model) {
            $data['user_id'] = $userId;
            $data['date']    = $date;
            return $this->create($data);
        }
        foreach ($data as $field => $value) {
            $model->$field += $value;
        }
        $model->save();
        $model->refresh();
        return $model;
    }

    public function one(array $condition = [], bool $fail = false, bool $lock = false)
    {
        $query = Model::query();
        $query->where($condition);
        if ($lock) {
            $query->lockForUpdate();
        }
        return $fail == true ? $query->firstOrFail() : $query->first();
    }

    public function find(int $id, bool $fail = false, bool $lock = false)
    {
        return $this->one(['id' => $id], $fail, $lock);
    }

    public function create(array $data)
    {
        $model = new Model();
        $model->fill($data);
        $model->save();
        $model->refresh();

        return $model;
    }

}